package com.southwind.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.southwind.vo.OrderMasterVO;
import com.southwind.entity.OrderDetail;
import com.southwind.entity.OrderMaster;
import com.southwind.form.OrderForm;
import com.southwind.service.IOrderDetailService;
import com.southwind.service.IOrderMasterService;
import com.southwind.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 订单表 前端控制器 买家端
 * </p>
 *
 * @author admin
 * @since 2021-04-18
 */
@RestController
@RequestMapping("/buyer/order")
@Slf4j
public class OrderMasterBuyerController {

    @Autowired
    private IOrderMasterService orderMasterService;

    @Autowired
    private IOrderDetailService orderDetailService;

    /**
     * 创建订单
     */
    @PostMapping("/create")
    public ResultVO<Map<String, String>> create(@Validated @RequestBody OrderForm orderForm, BindingResult bindingResult) {
        // @Validated进行数据校验，BindingResult接收校验结果
        if (bindingResult.hasErrors()) {
            log.error("【创建订单】，参数异常，orderForm={}", orderForm);
            String defaultMessage = bindingResult.getFieldError().getDefaultMessage();
            throw new RuntimeException(defaultMessage);
        }
        // 插入order_master
        String orderId = orderMasterService.insert(orderForm);
        Map<String, String> map = new HashMap<>();
        map.put("orderId", orderId);
        if (orderId != null) {
            return ResultVO.successWithData(map);
        }
        return ResultVO.failWithoutMsg();
    }

    /**
     * 订单列表
     */
    @GetMapping("/list/{buyerId}")
    public ResultVO<List<OrderMasterVO>> list(@PathVariable String buyerId) {
        log.info("订单列表, buyerId = {}", buyerId);
        QueryWrapper<OrderMaster> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("buyer_openid", buyerId);
        List<OrderMaster> list = orderMasterService.list(queryWrapper);
        ArrayList<OrderMasterVO> orderMasterVOList = new ArrayList<>();
        for (OrderMaster orderMaster : list) {
            OrderMasterVO orderMasterVO = new OrderMasterVO();
            BeanUtils.copyProperties(orderMaster, orderMasterVO);
            orderMasterVOList.add(orderMasterVO);
        }
        return ResultVO.successWithData(orderMasterVOList);
    }

    /**
     * 查询订单详情
     */
    @GetMapping("/detail/{buyerId}/{orderId}")
    public ResultVO<OrderMasterVO> list(@PathVariable String buyerId,
                                        @PathVariable String orderId) {
        log.info("查询订单详情, buyerId = {}, orderId = {}", buyerId, orderId);
        QueryWrapper<OrderMaster> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("buyer_openid", buyerId);
        queryWrapper.eq("order_id", orderId);
        // 查询订单
        OrderMaster orderMaster = orderMasterService.getOne(queryWrapper);
        if (orderMaster == null) {
            throw new RuntimeException("订单不存在！");
        }
        // 创建OrderMasterVO
        OrderMasterVO orderMasterVO = new OrderMasterVO();
        BeanUtils.copyProperties(orderMaster, orderMasterVO);
        // 查询订单详情
        QueryWrapper<OrderDetail> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("order_id", orderId);
        List<OrderDetail> orderDetailList = orderDetailService.list(queryWrapper1);
        orderMasterVO.setOrderDetailList(orderDetailList);
        return ResultVO.successWithData(orderMasterVO);
    }

    /**
     * 支付订单
     */
    @PutMapping("/pay/{buyerId}/{orderId}")
    public ResultVO pay(@PathVariable String buyerId,
                           @PathVariable String orderId) {
        log.info("支付订单, buyerId = {}, orderId = {}", buyerId, orderId);
        QueryWrapper<OrderMaster> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("buyer_openid", buyerId);
        queryWrapper.eq("order_id", orderId);
        // 查询订单
        OrderMaster orderMaster = orderMasterService.getOne(queryWrapper);
        if (orderMaster == null) {
            throw new RuntimeException("订单不存在！");
        }
        Integer orderStatus = orderMaster.getOrderStatus();
        if (orderStatus != 0) {
            throw new RuntimeException("订单状态错误！");
        }
        Integer payStatus = orderMaster.getPayStatus();
        if (payStatus != 0) {
            throw new RuntimeException("支付状态错误！");
        }
        // 支付订单
        orderMaster.setPayStatus(1);
        boolean b = orderMasterService.updateById(orderMaster);
        return b ? ResultVO.successWithoutData() : ResultVO.failWithoutMsg();
    }

    /**
     * 完结订单
     */
    @PutMapping("/finish/{orderId}")
    public ResultVO finish(@PathVariable String orderId) {
        log.info("完结订单, orderId = {}", orderId);
        QueryWrapper<OrderMaster> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", orderId);
        // 查询订单
        OrderMaster orderMaster = orderMasterService.getOne(queryWrapper);
        if (orderMaster == null) {
            throw new RuntimeException("订单不存在！");
        }
        Integer orderStatus = orderMaster.getOrderStatus();
        if (orderStatus != 0) {
            throw new RuntimeException("订单状态错误！");
        }
        // 完结订单
        orderMaster.setOrderStatus(1);
        boolean b = orderMasterService.updateById(orderMaster);
        return b ? ResultVO.successWithoutData() : ResultVO.failWithoutMsg();
    }

    /**
     * 取消订单
     */
    @PutMapping("/cancel/{buyerId}/{orderId}")
    public ResultVO cancel(@PathVariable String buyerId,
                           @PathVariable String orderId) {
        log.info("取消订单, buyerId = {}, orderId = {}", buyerId, orderId);
        QueryWrapper<OrderMaster> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("buyer_openid", buyerId);
        queryWrapper.eq("order_id", orderId);
        // 查询订单
        OrderMaster orderMaster = orderMasterService.getOne(queryWrapper);
        if (orderMaster == null) {
            throw new RuntimeException("订单不存在！");
        }
        Integer orderStatus = orderMaster.getOrderStatus();
        if (orderStatus != 0) {
            throw new RuntimeException("订单状态错误！");
        }
        // 取消订单
        orderMaster.setOrderStatus(2);
        boolean b = orderMasterService.updateById(orderMaster);
        return b ? ResultVO.successWithoutData() : ResultVO.failWithoutMsg();
    }
}

